<?php

namespace app\api\controller\common;

use app\common\controller\Api;
use think\facade\Db;
use app\service\Search as SearchSearch;

/**
 * di 搜索接口
 */
class Search extends Api
{
	protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected function initialize()
    {
        parent::initialize();
        
        set_time_limit(0);

        // return ajaxReturn("已达调用接口上限", -1, []);

    }
    public function test()
    {
        return 123;
    }

    /**
     * 表达式检索
     */
    public function expression()
    {
        // return ajaxReturn("已达调用接口上限", -1, []);
        //搜索表达式
        $exp = $this->request->param("exp", "", "trim");
        $page = $this->request->param("page", 1, "intval");
        $keywords = $this->request->param("keywords", "", "trim");
        $key = $this->request->param("key", "", "trim");

        $lssc = $this->request->param("lssc", "", "trim");
        $pdt = $this->request->param("pdt", "", "trim");

        if ($page < 1) {
            $page = 1;
        }

        if (!empty($keywords)) {
            $exp = "名称+摘要和说明+权利要求书+说明书全文=" . $keywords;

            if (!empty($key)) {
                $exp .= " AND 关键词=" . $key;
            }
        }

        // 简单法律状态 
        if (!empty($lssc)) {
            $exp .= " AND 当前权利状态=" . $lssc;
        }

        // 专利类型
        if (!empty($pdt)) {
            $exp .= " AND 专利类型=" . $pdt;
        }


        if (empty($exp)) {
            return ajaxReturn("successfully", 1, []);
        }


        //取出基本信息
        try {
            $result = (new SearchSearch())->experssion(['express' => $exp], $page, 10);
        } catch (\Exception $e) {
            return ajaxReturn('successfuly', 1, []);
        }

        if (empty($result['context']) || empty($result['context']['records'])) {
            return ajaxReturn('successfuly', 1, []);
        }
        $total = $result['total'];
        $patent_list = $result['context']['records'];


//        //取出法律状态
//        foreach ($patent_list as $k => $v) {
//            $patent_list[$k]['status'] = '';
//            $patent_list[$k]['event'] = '';
//            $lawStatus = Cache::get("laws_" . $v['pid']);
//            if (empty($lawStatus)) {
//                $result = (new \app\service\Search())->law(['pid' => $v['pid']]);
//                $lawStatus = $result['context']['records'][0];
//                Cache::set("laws_" . $v['pid'], $lawStatus, getNextMondayTime());
//            }
//
//            $patent = CacheService::GetPatentDetail($v['pid']);
//            $catalogPatent = $patent['catalogPatent'] ?? [];
//            $rd = $catalogPatent['rd'] ?? '';
//            $patent_list[$k]['status'] = Patent::getStatus($lawStatus,$rd);
//            $patent_list[$k]['event'] = Patent::getEvent($lawStatus,$catalogPatent);
//        }


        $return_list = [];
        foreach ($patent_list as $k => $v) {
            $v['lssc'] = $v['lssc'] ?? 0;
            if ($v['lssc'] == 1) {
                $status = '有效';
            } elseif ($v['lssc'] == 2) {
                $status = '无效';
            } elseif ($v['lssc'] == 3) {
                $status = '在审';
            } elseif ($v['lssc'] == 8) {
                $status = '不影响';
            } elseif ($v['lssc'] == 9) {
                $status = '不确定/待定';
            } else {
                $status = '暂无数据';
            }


            $return_list[$k] = [
                'pid' => $v['pid'] ?? '暂无数据',//pid
                'pns' => $v['pns'] ?? '暂无数据',//公开(公告)号
                'tic' => $v['tic'] ?? '暂无数据',//专利标题
                'apc' => $v['apc'] ?? '暂无数据',//当前申请(专利)人
                'asc' => $v['asc'] ?? '暂无数据',//专利权人
                'aspo' => $v['aspo'] ?? '暂无数据',//专利权人
                'inc' => $v['inc'] ?? '暂无数据',//发明人
                'ad' => !empty($v['ad']) ? date("Y-m-d", strtotime($v['ad'])) : '暂无数据',//申请日
                'pd' => !empty($v['pd']) ? date("Y-m-d", strtotime($v['pd'])) : '暂无数据',//公告(公开)日
                'ano' => $v['ano'] ?? '暂无数据',//申请号
                'crc' => $v['crc'] ?? '暂无数据',//代理机构
                'status' => $status,//法律状态
                'event' => $v['event'] ?? '暂无数据',//事件
                'absc' => $v['absc'] ?? '暂无数据',//摘要
                'pdt' => $v['pdt'] ?? '暂无数据',//摘要
            ];

            //缓存详情缩略图
            Cache::set("img_" . $v['pid'], $v['IMGO'] ?? '', getNextMondayTime());
        }

        //检索量每次+1
        //@Db::name("statistics")->where('id', 1)->inc("search_num")->update();
        // @Db::name("statistics")->insert([
        //     'user_id' => $this->user['id'],
        //     'type' => 1,
        //     'ctime' => time(),
        //     'num' => 1
        // ]);

        return ajaxReturn("successfully", 1, [
            'patent_list' => $return_list,
            'page' => [
                'total' => $total,
                'page' => $page,
                'page_row' => 10
            ]
        ]);
    }

    /**
     * 字段和表达式
     */
    public function fields()
    {
        $search_field = [
            '名称',
            '摘要和说明',
            '名称+摘要和说明',
            '名称+摘要和说明+权利要求书',
            '名称+摘要和说明+权利要求书+说明书全文',
            '权利要求书',
            '说明书全文',
            '背景技术',
            '发明内容',
            '具体实施方式',
            '附图说明',
            '关键词',
            '技术领域',
            '申请人',
            '专利权人',
            '发明人',
            '相关权利人',
            '代理人',
            '公布日',
            '申请日',
            '进入国家日',
            '最早优先权日',
            '申请号',
            '公布号',
            '优先权',
            '最早优先权',
            '简单同族',
            '引证文献',
            '申请人地址',
            '专利权人地址',
            '代理机构',
            '代理人地址',
            '审查员',
            '主审员',
            '申请人区域代码',
            '主权项',
        ];

        $exp = [
            'AND',
            'OR',
            'NOT'
        ];
        return ajaxReturn("successfully", 1, [
            'fields' => $search_field,
            'exp' => $exp
        ]);
    }

    /**
     * 专利智能(高级)检索
     */
    public function intelligence()
    {
        //搜索表达式
        $keywords = $this->request->param("keywords", "", "trim");
        $page = $this->request->param("page", 1, "intval");

        if ($page < 1) {
            $page = 1;
        }

        if (empty($keywords)) {
            return ajaxReturn("successfully", 1, []);
        }

        /*if(strpos($keywords,",") !== false){
            $arr = explode(',',$keywords);
            $keywords = "";
            foreach ($arr as $k=>$v){
                $keywords .= "名称=".$v." AND";
            }

            $keywords = rtrim($keywords,"AND");
        }*/
        $url_type = 0;//0专利智能(高级)检索 1表达式检索
        if(is_numeric($keywords) && strlen($keywords) == 12)// 数字 12位走申请号
        {
            $url_type = 1;
            $keywords = "申请号=" . $keywords;
        }else if( (is_numeric($keywords) && strlen($keywords) == 9) || strlen($keywords) == 10 )// 数字 9位 和10位走公开号
        {
            $url_type = 1;
            $keywords = "公布号=" . $keywords;
        }else if (strlen($keywords) == 13) { //普通13位
            $start = substr($keywords, 0, -1);
            $end = substr($keywords, -1, 1);
            $keywords = 'CN'.$start.'.'.$end;
        }else if(strpos($keywords, '.') == 12 && strlen($keywords) == 14){
            // 只加点.
            $keywords = 'CN'.$keywords;
        }
        // 只加CN
        else if (stripos($keywords, 'cn') === 0) {
            $keywords1 = str_ireplace('cn', '', $keywords);
            if (strlen($keywords1) == 13) {
                $start = substr($keywords1, 0, -1);
                $end = substr($keywords1, -1, 1);
                $keywords = 'CN'.$start.'.'.$end;
            }
        } 


        //取出基本信息
        try {
            if($url_type == 1)
            {
                $result = (new SearchSearch())->experssion(['express' => $keywords], $page, 10);
            }else
            {
                $result = (new SearchSearch())->intell(['text' => $keywords], $page, 10);
            }
           
        } catch (\Exception $e) {
            return ajaxReturn('successfuly', 1, []);
        }

        if (empty($result['context']) || empty($result['context']['records'])) {
            return ajaxReturn('successfuly', 1, []);
        }
        $total = $result['total'];
        $patent_list = $result['context']['records'];

//        //取出法律状态
//        foreach ($patent_list as $k => $v) {
//            $patent_list[$k]['status'] = '';
//            $patent_list[$k]['event'] = '';
//            $lawStatus = Cache::get("laws_" . $v['pid']);
//            if (empty($lawStatus)) {
//                $result = (new \app\service\Search())->law(['pid' => $v['pid']]);
//                $lawStatus = $result['context']['records'][0];
//                Cache::set("laws_" . $v['pid'], $lawStatus, getNextMondayTime());
//            }
//
//            $patent = CacheService::GetPatentDetail($v['pid']);
//            $catalogPatent = $patent['catalogPatent'] ?? [];
//            $rd = $catalogPatent['rd'] ?? '';
//            $patent_list[$k]['status'] = Patent::getStatus($lawStatus,$rd);
//            $patent_list[$k]['event'] = Patent::getEvent($lawStatus,$catalogPatent);
//        }

        $return_list = [];
        foreach ($patent_list as $k => $v) {
            $v['lssc'] = $v['lssc'] ?? 0;
            if ($v['lssc'] == 1) {
                $status = '有效';
            } elseif ($v['lssc'] == 2) {
                $status = '无效';
            } elseif ($v['lssc'] == 3) {
                $status = '在审';
            } elseif ($v['lssc'] == 8) {
                $status = '不影响';
            } elseif ($v['lssc'] == 9) {
                $status = '不确定/待定';
            } else {
                $status = '暂无数据';
            }

            $return_list[$k] = [
                'pid' => $v['pid'] ?? '暂无数据',//pid
                'pns' => $v['pns'] ?? '暂无数据',//公开(公告)号
                'tic' => $v['tic'] ?? '暂无数据',//专利标题
                'apc' => $v['apc'] ?? '暂无数据',//当前申请(专利)人
                'asc' => $v['asc'] ?? '暂无数据',//专利权人
                'inc' => $v['inc'] ?? '暂无数据',//发明人
                'ad' => !empty($v['ad']) ? date("Y-m-d", strtotime($v['ad'])) : '暂无数据',//申请日
                'pd' => !empty($v['pd']) ? date("Y-m-d", strtotime($v['pd'])) : '暂无数据',//公告(公开)日
                'ano' => $v['ano'] ?? '暂无数据',//申请号
                'crc' => $v['crc'] ?? '暂无数据',//代理机构
                'status' => $status,//法律状态
                'event' => $v['event'] ?? '暂无数据',//事件
                'absc' => $v['absc'] ?? '暂无数据',//摘要
                'pdt' => $v['pdt'] ?? '暂无数据',//摘要
            ];
        }

        //检索量每次+1
        //@Db::name("statistics")->where('id', 1)->inc("search_num")->update();
        // @Db::name("statistics")->insert([
        //     'user_id' => $this->user['id'],
        //     'type' => 1,
        //     'ctime' => time(),
        //     'num' => 1
        // ]);

        return ajaxReturn("successfully", 1, [
            'patent_list' => $return_list,
            'page' => [
                'total' => $total,
                'page' => $page,
                'page_row' => 10
            ]
        ]);

    }

    /**
     * 左侧筛选
     */
    public function left()
    {
        //$output = Console::call('user');
        //return $output->fetch();
    }

    /**
     * 专利详情==》摘要
     */
    public function intro()
    {
        // return ajaxReturn("已达调用接口上限", -1, []);
        $pid = $this->request->param('pid', '', 'trim');
        $type = $this->request->param("type", 0, 'intval');
        $cost_num = AuthLogic::GetAuthFieldData($this->user['id'], 'cost_warning_num');
        if ($type == 8) {
            // 费用信息
            $info = SearchLogic::task(0, $pid, $this->user['id'], $cost_num, $this->user['is_admin']);
            $info['data'] = $info['data']['feePaymentInformations'] ?? [];
        }else{
            $info = SearchLogic::task($type, $pid, $this->user['id'], $cost_num, $this->user['is_admin']);
        }

        return ajaxReturn($info['msg'], $info['code'], $info['data']);
    }

    /**
     * 下载专利
     */
    public function download()
    {
        $param = $this->request->param();
        $pid = !empty($param['pid']) ? $param['pid'] : '';

        $pdf = Cache::get("down_" . $pid);
        if (empty($pdf)) {
            //pdf下载链接
            $result2 = (new SearchSearch())->download(['pid' => $pid]);
            if ("" != $result2) {
                $pdf = $result2[0]['nginxPath'];
            } else {
                $pdf = "";
            }
            Cache::set("down_" . $pid, $pdf, getNextMondayTime());
        }

        $zl = uniqid("zl_");
        $pdf2 = downImgRar("http://" . $pdf, $zl, "pdf");
        forceDownload($pdf2);
        @unlink($pdf2);
        exit();
    }

    /**
     * 拼接表达式
     */
    public function getExpression()
    {
        $exp = "";
        $param = $this->request->param('field');
        if (empty($param)) {
            return ajaxReturn('successfully', 1, [
                'text' => $exp
            ]);
        }

        $key = 0;
        //开始拼接表达式
        foreach ($param as $k => $v) {
            if (('' != $v['select']) && ('' != $v['input']) && $k != 0) {

                // 默认连接符为AND
                if ($v['name'] == '') {
                    $param[$k]['name'] = 'AND'; 
                    $v['name'] = 'AND'; 
                }

                $exp .= $v['name'] . " " . $v['select'] . "=" . $v['input'] . " ";

                // 取第一个有数据的数组的键值
                if ($key == 0) {
                    $key = $k;
                }

            }
        }

        $exp = ltrim($exp, "OR");
        $exp = ltrim($exp, "AND");
        $exp = ltrim($exp, "NOT");
        $exp = trim($exp);

        // 不填主字段则不加括号
        if ($param[0]['select'] != '' && $param[0]['input'] != '') {
            if($key){
                $exp = $param[0]['select']."=".$param[0]['input']." ".$param[$key]['name']." (".$exp.")";
            }else{
                $exp = $param[0]['select']."=".$param[0]['input'];
            }
            
        }

        return ajaxReturn('successfully', 1, [
            'text' => $exp
        ]);
    }





    /**
     * 法律文书检索
     */
    public function cseSearch()
    {
        $param = $this->request->param();
        $page = !empty($param['page']) ? $param['page'] : 1;
        $exp = $param['exp'] ?? '';

        if (empty($exp)) {
            return ajaxReturn('successfully', 1, []);
        }

        $result = (new SearchSearch())->cseList(['express' => $exp], $page);
        if (($result['errorCode'] != "000000") || empty($result['context']) || empty($result['context']['records'])) {
            return ajaxReturn('successfully', 1, []);
        }

        return ajaxReturn('success', 1, [
            'list' => $result['context']['records'],
            'page' => [
                'page_size' => 10,
                'page' => $page,
                'count' => $result['total']
            ]
        ]);
    }

    
    /**
     * 诉讼详情
     */
    public function cseDetail()
    {
        $cid = $this->request->param('cid', '', 'trim');
        $result2 = (new SearchSearch())->cseDetail(['id' => $cid]);
        //dump($result2);
        $ret = isset($result2['context']['records'][0]['referee']['html']) ? Html::ParseHtml($result2['context']['records'][0]['referee']['html']) : '';
        return ajaxReturn('successfully', 1, [
            'html' => $ret
        ]);
    }

    

    /**
     * 下载
     */
    public function cseDownload()
    {
        $id = input('cid');
        $result = (new SearchSearch())->cseDownload(['id' => $id]);
        $filename = $result['context']['records'][0]['pdfPath'];
        
        return ajaxReturn('successfully', 1, [
            'pdf' => $filename
        ]);
    }


    /**
     * 商标搜索
     */
    public function trademark_list()
    {
        //搜索表达式
        $exp = $this->request->param("express", "", "trim");
        $page = $this->request->param("page", 1, "intval");

        //取出基本信息
        try {
            $result = (new SearchSearch())->trademarkList(['express' => $exp], $page, 10);
        } catch (\Exception $e) {
            return ajaxReturn('successfuly', 1, []);
        }

        if (empty($result['context']) || empty($result['context']['records'])) {
            return ajaxReturn('successfuly', 1, []);
        }

        $total = $result['total'];
        $patent_list = $result['context']['records'];

        return ajaxReturn("successfully", 1, [
            'patent_list' => $patent_list,
            'page' => [
                'total' => $total,
                'page' => $page,
                'page_row' => 10
            ]
        ]);
    }  


    /**
     * 诉讼详情
     */
    public function trademark_info()
    {
        $tid = $this->request->param('tid', '', 'trim');
        $result2 = (new SearchSearch())->trademarkInfo(['id' => $tid]);
        // var_dump($result2);
        $ret = isset($result2['context']['records'][0]) ? $result2['context']['records'][0] : '';
        return ajaxReturn('successfully', 1, $ret);
    }


}